<template>
  <div class="login-container">
    <el-card class="box-card">
      <!-- 标题 -->
      <div class="title"></div>
      <el-form ref="form" :model="user" :rules="rules">
        <el-form-item prop="username">
          <!-- 用户名 -->
          <el-input prefix-icon="el-icon-s-custom" placeholder="请输入用户名" v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <!-- 密码 -->
          <el-input
            prefix-icon="el-icon-lock"
            placeholder="请输入密码"
            type="password"
            show-password
            v-model="user.password"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <!-- 按钮 -->
          <el-button type="primary" @click="login">登录</el-button></el-form-item
        >
      </el-form>
      <el-link :underline="false" @click="$router.push('/reg')">还没有账户,去注册</el-link>
    </el-card>
  </div>
</template>
<script>
import { loginAPI } from '@/api/user'
export default {
  name: 'MyLogin',
  data() {
    return {
      user: { username: '', password: '' },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{1,10}$/, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const { data: res } = await loginAPI(this.user)
          console.log(res)
          if (res.code === 0) {
            // 提示框，清空表单，跳转
            this.$message.success(res.message)
            this.$refs.form.resetFields()
            this.$router.push('/')
            this.$store.commit('user/updateToken', res.token)
          } else {
            this.$message.error(res.message)
            return false
          }
        }
      })
    }
  }
}
</script>
<style>
.login-container {
  background: url('@/assets/images/login_bg.jpg') no-repeat;
  background-size: cover;
  height: 100%;
}
.el-card {
  width: 400px;
  /* height: 310px; */
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.title {
  height: 40px;
  background: url(@/assets/images/login_title.png) top center no-repeat;
}
.el-button {
  width: 100%;
}
</style>
